<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="input-wrapper">
        <input 
          class="search-input" 
          placeholder="请输入会议名称/关键词" 
          v-model="searchKeyword"
          @confirm="handleSearch"
        />
        <uni-icons 
          class="search-icon" 
          type="search" 
          size="20" 
          color="#999" 
          @click="handleSearch"
        />
      </view>
      <button 
        class="cancel-button" 
        @click="handleCancelSearch"
        v-if="searchKeyword"
      >
        取消
      </button>
    </view>

    <!-- 日期分段器 -->
    <scroll-view scroll-x class="segmented-control">
      <view 
        v-for="(item, index) in dateOptions" 
        :key="index" 
        :class="['segment-item', activeDate === item.value ? 'active' : '']"
        @click="handleFilterChange(item.value, 'date')"
      >
        {{ item.text }}
      </view>
    </scroll-view>

    <!-- 类型分段器 -->
    <scroll-view scroll-x class="segmented-control">
      <view 
        v-for="(item, index) in typeOptions" 
        :key="index" 
        :class="['segment-item', activeType === item.value ? 'active' : '']"
        @click="handleFilterChange(item.value, 'type')"
      >
        {{ item.text }}
      </view>
    </scroll-view>

    <!-- 卡片列表 -->
    <scroll-view class="scroll-view" scroll-y>
      <!-- 加载状态 -->
      <view v-if="isLoading" class="loading">
        <uni-load-more status="loading"></uni-load-more>
      </view>

      <!-- 分组渲染 -->
      <view v-for="group in groupedCards" :key="group.title">
        <!-- 分组标题 -->
        <view class="group-title">
          {{ group.title }}
        </view>

        <!-- 分组中的卡片 -->
        <view v-for="card in group.cards" :key="card.meetId" class="card-container">
          <view class="card">
            <!-- 封面图及右上角按钮 -->
            <view class="cover-wrapper" @click="gotoDetail(card.meetId)">
              <image class="cover-image" :src="card.coverImage" mode="aspectFill"></image>
              <button class="playback-button">
                {{ card.playback }}
              </button>
            </view>

            <!-- 文字描述部分 -->
            <view class="description">
              <text class="title">{{ card.title }}</text>
              <view class="info-row">
                <uni-icons type="notification" size="20" color="#fff"></uni-icons>
                <text class="details">时间：{{ card.time }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="map-pin-ellipse" size="20" color="#fff"></uni-icons>
                <text class="details">地点：{{ card.location }}</text>
              </view>
              <view class="button-container">
                <button class="subscribe-button" @click.stop="handleSubscribe(card.meetId, $event)">订阅</button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态提示 -->
      <view v-if="!isLoading && meetings.length === 0" class="empty-tip">
        暂无数据
      </view>
    </scroll-view>
  </view>
</template>


<script setup>
import { ref, computed } from 'vue';
import { getFilteredMeetings, subscribeMeeting } from '@/api/meet.js';

// 分段器选项配置
const dateOptions = [
  { value: 'ALL', text: '全部议程' },
    { value: '2025-03-01', text: '3月1日' },
  { value: '2025-03-29', text: '3月29日' },
  { value: '2025-05-08', text: '5月8日' },
  { value: '2025-05-17', text: '5月17日' },
  { value: '2025-05-18', text: '5月18日' }
];


const typeOptions = [
  { value: 'ALL', text: '全部类型' },
  { value: 'MAIN', text: '主论坛' },
  { value: 'PARALLEL', text: '平行会议' },
  { value: 'SCIENCE', text: '科普论坛' },
  { value: 'PRODUCT', text: '新品发布' },
  { value: 'ECOLOGY', text: '生态合作论坛' }
];

// 状态管理
const activeDate = ref('ALL');
const activeType = ref('ALL');
const meetings = ref([]);
const isLoading = ref(false);
const searchKeyword = ref('');

// 分段器选择处理
const handleFilterChange = (value, filterType) => {
  if(filterType === 'date') {
    activeDate.value = value;
  } else if(filterType === 'type') {
    activeType.value = value;
  }
  fetchData();
};

// 数据获取
const fetchData = async () => {
  try {
    isLoading.value = true;
    
    const params = {
      type: activeType.value,
      keyword: searchKeyword.value,
      date: activeDate.value
    };
    
    console.log('查询参数:', params);
    const res = await getFilteredMeetings(params);
    
    // 检查数据格式并处理
    if (Array.isArray(res)) {
      meetings.value = res.map(card => {
        // 确保每个卡片都有必要的字段，防止前端渲染错误
        return {
          id: card.id,
          meetId: card.meetId || card.id, // 如果没有meetId，使用id作为后备
          title: card.title || '未命名会议',
          date: card.date || '日期未定',
          time: card.time || '时间未定',
          location: card.location || '地点未定',
          coverImage: card.coverImage || '/static/icon/meet.image/AI引领.webp',
          playback: card.isOnline?'支持线上':'只线下',
          isOnline:card.isOnline?1:0,
          type: card.type || '未分类',
          browse: card.browse || 3306,
          video: card.video || ''
        };
      });
      
      console.log('处理后的会议数据:', meetings.value);
    } else {
      console.error('返回数据格式不正确:', res);
      meetings.value = [];
    }
  } catch (error) {
    console.error('获取会议列表失败:', error);
    meetings.value = [];
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    isLoading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  fetchData();
};

// 取消搜索
const handleCancelSearch = () => {
  searchKeyword.value = '';
  fetchData();
};

// 分组逻辑（带字段保护）
const groupedCards = computed(() => {
  const groups = {};

  (meetings.value || []).forEach((card) => {
    // 解析日期格式为 "YYYY-MM-DD"，忽略时间部分
    let dateKey = '未知日期';
    if (card.date) {
      try {
        // 处理多种可能的日期格式
        const datePart = card.date.includes(' ') ? card.date.split(' ')[0] : card.date;
        const dateParts = datePart.split('-');
        if (dateParts.length >= 3) {
          const [year, month, day] = dateParts;
          dateKey = `${parseInt(month)}月${parseInt(day)}日`; // 格式化为 "3月1日"，去掉前导零
        } else {
          dateKey = card.date; // 保留原始日期
        }
      } catch (e) {
        console.error('日期解析失败:', card.date, e);
      }
    }

    if (!groups[dateKey]) {
      groups[dateKey] = { title: dateKey, cards: [] };
    }
    groups[dateKey].cards.push(card);
  });

  // 对group进行排序
  return Object.values(groups).sort((a, b) => {
    // 提取月和日进行比较
    const getMonthDay = (title) => {
      const match = title.match(/(\d+)月(\d+)日/);
      if (match) {
        return { month: parseInt(match[1]), day: parseInt(match[2]) };
      }
      return { month: 0, day: 0 }; // 默认值
    };
    
    const aDate = getMonthDay(a.title);
    const bDate = getMonthDay(b.title);
    
    // 先按月份排序，再按日期排序
    if (aDate.month !== bDate.month) {
      return aDate.month - bDate.month;
    }
    return aDate.day - bDate.day;
  });
});

//跳转到详情页
const gotoDetail = (meetId) => {
  if (!meetId) {
    console.error('缺少meetId参数，无法跳转到详情页');
    uni.showToast({
      title: '无法查看详情，会议ID缺失',
      icon: 'none'
    });
    return;
  }
  
  console.log('准备跳转到会议详情页，meetId:', meetId);
  
  // 查找会议详细信息
  const meetingCard = meetings.value.find(item => item.meetId === meetId || item.id === meetId);
  if (!meetingCard) {
    console.error('未找到对应的会议信息，meetId:', meetId);
    uni.showToast({
      title: '会议信息加载失败',
      icon: 'none'
    });
    return;
  }
  
  // 检查会议是否支持线上
  // console.log("isonline:",meetingCard.isOnline);
  if (!meetingCard.isOnline) {
    console.log('该会议不支持线上参与:', meetingCard.title);
    uni.showModal({
      title: '提示',
      content: '该会议仅支持线下参与，无法查看详情',
      showCancel: false
    });
    return;
  }
  
  console.log('携带的会议数据:', meetingCard);
  
  // 将数据编码为URL参数
  const params = {
    meetId: meetId.toString(),
    title: meetingCard.title || '未命名会议',
    time: meetingCard.time || '时间待定',
    location: meetingCard.location || '地点待定',
    type: meetingCard.type || '',
    browse: (meetingCard.browse || 0).toString(),
    video: meetingCard.video || ''
  };
  
  // 构建URL查询字符串
  const queryString = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
  
  console.log('跳转URL查询参数:', queryString);
  
  // 导航到详情页
  uni.navigateTo({
    url: `/pages/huiyi/detail?${queryString}`,
    success: () => {
      console.log('成功跳转到详情页');
    },
    fail: (error) => {
      console.error('跳转到详情页失败:', error);
      uni.showToast({
        title: '跳转失败，请重试',
        icon: 'none'
      });
    }
  });
};

// 处理订阅按钮点击
const handleSubscribe = async (meetId, event) => {
  // 阻止事件冒泡，避免触发卡片的点击事件
  event.stopPropagation();
  
  console.log('订阅会议，meetId:', meetId);
  try {
    uni.showLoading({
      title: '订阅中...',
      mask: true
    });
    
    const result = await subscribeMeeting(meetId);
    
    uni.hideLoading();
    
    if (result.success) {
      uni.showToast({
        title: '订阅成功',
        icon: 'success'
      });
      
      // 更新订阅状态（可选功能，如需实现需要后端支持）
      // meetings.value = meetings.value.map(meeting => {
      //   if (meeting.meetId === meetId) {
      //     return { ...meeting, isSubscribed: true };
      //   }
      //   return meeting;
      // });
    } else {
      uni.showToast({
        title: result.message || '订阅失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('订阅失败:', error);
    uni.showToast({
      title: '订阅失败，请稍后再试',
      icon: 'none'
    });
  }
};

// 初始化加载
fetchData();
</script>


<style scoped>
/* 外层容器 */
.container {
  padding: 20rpx;
}
/* 搜索栏容器 */
.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f5f5f5;
  
  margin-bottom: 20rpx;
}

/* 输入框包裹容器 */
.input-wrapper {
  position: relative; /* 作为图标定位的父容器 */
  flex: 1; /* 占据剩余空间 */
  margin-right: 20rpx; /* 为取消按钮预留间距 */
}

/* 输入框样式 */
.search-input {
  width: 85%;
  padding: 0 60rpx 0 20rpx; /* 右侧留出图标空间 */
  height: 60rpx;
  font-size: 28rpx;
  background: white;
}

/* 搜索图标（定位在输入框内部右侧） */
.search-icon {
  position: absolute;
  right: 20rpx; /* 相对于输入框右侧定位 */
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
}

/* 取消按钮 */
.cancel-button {
  padding: 0 20rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  color: #3AB54A;
  background: transparent;
}
/* 滚动视图 */
.scroll-view {
  width: 100%;
  height: calc(100vh - 150rpx); /* 调整滚动区域高度 */
}

/* 卡片容器 */
.card-container {
  margin-bottom: 40rpx; /* 设置卡片之间的垂直间距 */
}

/* 卡片样式 */
.card {
  width: 90%;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin: 0 auto; /* 居中显示 */
  transition: transform 0.2s, box-shadow 0.2s; /* 添加过渡效果 */
  cursor: pointer; /* 显示手型光标 */
}

/* 卡片悬停效果 */
.card:hover {
  transform: translateY(-5rpx);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

/* 卡片点击效果 */
.card:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 封面图片 */
.cover-image {
  display: block;
  width: 100%;
  height: 200px; /* 根据需要调整高度 */
}

/* 描述部分 */
.description {
  background-color: #123e7d; /* 蓝色背景 */
  padding: 10px;
  color: white;
  position: relative; /* 为按钮定位做准备 */
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 23px;
  margin-left: 10px;
  display: block;
  margin-top: 15px;
}

.info-row {
  display: flex;
  align-items: center; /* 图标和文字垂直对齐 */
  margin-bottom: 4px;
  margin-left: 10px;
}

.info-row uni-icons {
  margin-right: 8px; /* 图标与文字的间距 */
}

.details {
  font-size: 11px;
  line-height: 1.4;
}

.button-container {
  position: absolute;
  right: 15px;
  bottom: 40px;
}

.subscribe-button {
  background-color: #48ad9c;
  color: white;
  font-size: 11px;
  padding: 0px 5px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s; /* 添加过渡效果 */
}

.subscribe-button:hover {
  background-color: #3a9c8c;
}

.subscribe-button:active {
  background-color: #2d8a7a;
}

.segment-item.active {
  font-weight: bold;
  transition: all 0.3s;
}
.container {
  padding: 20rpx;
}

.segmented-control {
  display: flex;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  margin-bottom: 20rpx;
}

.segment-item {
  display: inline-block;
  padding: 15rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  text-align: center;
  cursor: pointer;
  position: relative; /* 用于定位下划线 */
}

/* 选中状态 */
.segment-item.active {
  color: #3AB54A; /* 文字颜色 */
}

/* 下划线 */
.segment-item.active::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 4rpx; /* 下划线高度 */
  background-color: #3AB54A; /* 下划线颜色 */
  border-radius: 2rpx; /* 圆角效果 */
}

/* 滚动条样式隐藏 */
.segmented-control::-webkit-scrollbar {
  display: none;
}
/* 保留原有样式，新增以下状态样式 */
.loading {
  padding: 20px;
  text-align: center;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px;
}
/* 分组标题样式 */
.group-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  padding: 20rpx;
  background-color: #f5f5f5;
}

/* 封面图容器 */
.cover-wrapper {
  position: relative;
}

/* 封面图右上角按钮 */
.playback-button {
  position: absolute;
  right: 10rpx;
  top: 10rpx;
  font-size: 24rpx;
  padding: 5rpx 10rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 5rpx;
  border: none;
}

</style>